package yx.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import yx.dao.BaseDaoInt;
import yx.model.SmUser;
import yx.utils.Encrypt;
import yx.utils.SystemProperties;
import yx.vo.DatagridVO;
import yx.vo.UserVO;

@Service("userService")
public class UserServiceImpl implements UserServiceInt {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(UserServiceImpl.class);
	
	private BaseDaoInt<SmUser> userDao;

	public BaseDaoInt<SmUser> getUserDao() {
		return userDao;
	}

	@Autowired
	public void setUserDao(BaseDaoInt<SmUser> userDao) {
		this.userDao = userDao;
	}

	@Override
	public UserVO save(UserVO user) {
		SmUser t = new SmUser();
		t.setUserName(user.getUserName());
		t.setPassword(user.getPassword());
		BeanUtils.copyProperties(user, t, new String[]{"password"});
		t.setPassword(Encrypt.e(user.getPassword()));
		t.setOptTime(new Timestamp(System.currentTimeMillis())); // 需要修改
		
		userDao.save(t);
		BeanUtils.copyProperties(t, user);
		return user;
	}

	@Override
	public UserVO login(UserVO user) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userName", user.getUserName());
		params.put("password", Encrypt.e(user.getPassword()));
		SmUser u = userDao.get("from SmUser t where t.userName = :userName and t.password = :password", params);
		if(u != null){
		    BeanUtils.copyProperties(u, user);
			return user;
		}
		return null;
	}

	@Override
	public DatagridVO datagrid(UserVO user) {
		DatagridVO dg = new DatagridVO();
		String hql = "from SmUser t";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(user, hql, params);
		String totalHql = "select count(*) "+hql;
		hql = addOrder(user, hql);
		List<SmUser> l = userDao.find(hql,params,user.getPage(),user.getRows());
		List<UserVO> nl = new ArrayList<UserVO>();
		changeModel(l, nl);
		dg.setTotal(userDao.count(totalHql,params));
		dg.setRows(nl);
		return dg;
	}

	private void changeModel(List<SmUser> l, List<UserVO> nl) {
		if(l != null && l.size() > 0){
			for(SmUser t : l){
				UserVO u = new UserVO();
				BeanUtils.copyProperties(t, u);
				nl.add(u);
			}
		}
	}

	private String addOrder(UserVO user, String hql) {
		if(user.getSort() != null || user.getOrder() != null){
			hql += " order by "+user.getSort()+" " + user.getOrder();
		}
		return hql;
	}

	private String addWhere(UserVO user, String hql, Map<String, Object> params) {
		if(user.getUserName() != null && !"".equals(user.getUserName().trim())){
			hql += " where t.user_name like :userName";
			params.put("name", "%%"+user.getUserName().trim()+"%%");
		}
		return hql;
	}

	@Override
	public void remove(String ids) {
//		for(String id : ids.split(",")){
//			SmUser u = userDao.get(SmUser.class, id);
//			if(u != null){
//				userDao.delete(u);				
//			}
//		}
		String[] nids = ids.split(",");
		String hql = "delete SmUser t where t.id in (";
		for(int i=0;i<nids.length;i++){
			if(i>0){
				hql += ",";
			}
			hql += "'" + nids[i] + "'";
		}
		hql += ")";
		userDao.executeHql(hql);
	}

	@Override
	public UserVO edit(UserVO user) {
		SmUser t = userDao.get(SmUser.class, user.getId());
		t.setEmail(user.getEmail());
		t.setGender(user.getGender());
		t.setLastModifyDate(new Timestamp(System.currentTimeMillis()));
		t.setLockFlag(user.getLockFlag());
		t.setMobile(user.getMobile());
		t.setRealName(user.getRealName());
		t.setRoleCode(user.getRoleCode());
		t.setPhone(user.getPhone());
		userDao.update(t);
		BeanUtils.copyProperties(user, t, new String[] { "id","password" });
		return user;
	}
	
	
	@Override
    public void lockingUser(String ids) {
	    String[] nids = ids.split(",");
        String hql = "update SmUser t set t.lockFlag='1' where t.id in (";
        for(int i=0;i<nids.length;i++){
            if(i>0){
                hql += ",";
            }
            hql += "'" + nids[i] + "'";
        }
        hql += ")";
        userDao.executeHql(hql);
    }
	
	@Override
    public void activatingUser(String ids) {
	    String[] nids = ids.split(",");
        String hql = "update SmUser t set t.lockFlag='0' where t.id in (";
        for(int i=0;i<nids.length;i++){
            if(i>0){
                hql += ",";
            }
            hql += "'" + nids[i] + "'";
        }
        hql += ")";
        userDao.executeHql(hql);
    }
	
	@Override
    public void resetPasswordUser(String ids) {
        String[] nids = ids.split(",");
        String defaultPwd =Encrypt.e(SystemProperties.get("DEFAULT_PASSWORD").toString()); 
        String hql = "update SmUser t set t.password='"+defaultPwd+"' where t.id in (";
        for(int i=0;i<nids.length;i++){
            if(i>0){
                hql += ",";
            }
            hql += "'" + nids[i] + "'";
        }
        hql += ")";
        userDao.executeHql(hql);
    }


}
